<template>
  <div class="custom-config">
    <vxe-table
      ref="table"
      :data="tableColumnList"
      :size="defaultFormItemSize"
      header-cell-class-name="table-header-gray"
      :row-config="{ height: 50, isHover: true, drag: true }"
      height="400px"
    >
      <vxe-column type="seq" width="60px" title="序号" />
      <vxe-column title="表格列名" field="showName" />
      <vxe-column title="是否显示" field="show">
        <template v-slot="scope">
          <el-switch v-model="scope.row.show" />
        </template>
      </vxe-column>
      <vxe-column drag-sort width="60px" title="排序" />
    </vxe-table>
    <div class="menu-box">
      <el-button :size="defaultFormItemSize" @click="onCancel">取消</el-button>
      <el-button type="primary" :size="defaultFormItemSize" @click="onSaveClick">保存</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { VxeTable, VxeColumn } from 'vxe-table';
import { ANY_OBJECT } from '@/types/generic';
import { DialogProp } from '@/components/Dialog/types';
import { traverseTree } from '@/common/utils';
import { useThirdParty } from '@/components/thirdParty/hooks';
import { ThirdProps } from '@/components/thirdParty/types';

defineOptions({
  name: 'CustomConfig',
});

interface IProps extends ThirdProps {
  data?: ANY_OBJECT[];
  // 当使用Dialog.show弹出组件时，须定义该prop属性，以便对dialog进行回调
  dialog?: DialogProp<ANY_OBJECT | ANY_OBJECT[] | undefined>;
}

const props = withDefaults(defineProps<IProps>(), {});
const table = ref(null);
const { thirdParams, onCloseThirdDialog } = useThirdParty(props);

const dialogParams = computed(() => {
  return {
    data: props.data || thirdParams.value.data,
  };
});

const tableColumnList = ref([]);

const onCancel = () => {
  if (props.dialog?.cancel) {
    props.dialog.cancel(false);
  } else {
    onCloseThirdDialog(false);
  }
};

const onSaveClick = () => {
  if (props.dialog) {
    const { fullData } = table.value.getTableData();
    (fullData || []).forEach((item, index) => {
      item.showOrder = index + 1;
    });
    props.dialog.submit(tableColumnList.value);
  } else {
    onCloseThirdDialog(true, dialogParams.value.data, tableColumnList.value);
  }
};

onMounted(() => {
  traverseTree(dialogParams.value.data || [], item => {
    tableColumnList.value.push({
      ...item,
    });
  });
  tableColumnList.value.sort((a, b) => a.showOrder - b.showOrder);
});
</script>

<style scoped>
.custom-config .menu-box {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  width: 100%;
  margin-top: 15px;
}
</style>
